package com.markerhub.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.ClassUpdateDto;
import com.markerhub.common.dto.UnitUpdateDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.Course;
import com.markerhub.entity.CourseLearnUnit;
import com.markerhub.entity.ManagerActivity;
import com.markerhub.entity.ManagerClass;
import com.markerhub.service.CourseLearnUnitService;
import com.markerhub.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/course-learn-unit")
public class CourseLearnUnitController {
    @Autowired
    CourseLearnUnitService courseLearnUnitService;

    @Autowired
    private CourseService courseService; // 需要注入CourseService

    @GetMapping("/student/units")
    public Result getStudentUnits(@RequestParam Integer studentId) {
        try {
            List<Map<String, Object>> units = courseLearnUnitService.getStudentUnits(studentId);
            return Result.succ(units);
        } catch (Exception e) {
            log.error("获取学生课程单元失败", e);
            return Result.fail("获取课程单元失败");
        }
    }


    @RequiresAuthentication
    @GetMapping("/units")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage,
                       @RequestParam(required = false) Integer teacherId) {

        Page page = new Page(currentPage, 5);
        // 如果提供了teacherId，先查询该教师的所有课程ID
        if (teacherId != null) {
            // 查询该教师的所有课程
            List<Course> teacherCourses = courseService.list(
                    new QueryWrapper<Course>()
                            .eq("teacher_id", teacherId)
            );
            // 获取课程ID列表
            List<Integer> courseIds = teacherCourses.stream()
                    .map(Course::getId)
                    .collect(Collectors.toList());
            // 如果教师没有课程，返回空结果
            if (courseIds.isEmpty()) {
                return Result.succ(new Page());
            }
            // 查询这些课程关联的单元
            IPage pageData = courseLearnUnitService.page(page,
                    new QueryWrapper<CourseLearnUnit>()
                            .in("course_id", courseIds)
            );
            return Result.succ(pageData);
        }
        // 如果没有提供teacherId，返回所有单元（保持原有功能）
        IPage pageData = courseLearnUnitService.page(page, new QueryWrapper<CourseLearnUnit>());
        return Result.succ(pageData);
    }

    @RequiresAuthentication
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdateCourse(@RequestBody UnitUpdateDto unitUpdateDto) {
     log.info(unitUpdateDto.getUnitTitle());

       CourseLearnUnit unit=new CourseLearnUnit();
        if (unitUpdateDto.getId() != null) {
            unit.setId(unitUpdateDto.getId()); // 设置课程ID用于更新
        }
        unit.setCourseId(unitUpdateDto.getCourseId());
        unit.setStatus(unitUpdateDto.getStatus());
        unit.setUnitTitle(unitUpdateDto.getUnitTitle());
        unit.setUnitIntroduce(unitUpdateDto.getUnitIntroduce());
        unit.setDocPath(unitUpdateDto.getDocPath());
        unit.setIsChpt(unitUpdateDto.getIsChpt());
        unit.setLearningScore(unitUpdateDto.getLearningScore());


        // 3. 保存课程信息
        courseLearnUnitService.saveOrUpdate(unit);

        return Result.succ("教学单元保存成功");
    }

    @RequiresAuthentication
    @DeleteMapping("/delete/{id}")
    public Result deleteUnit(@PathVariable Long id) {
        boolean isDeleted = courseLearnUnitService.removeById(id);
        if (isDeleted) {
            return Result.succ("教学单元删除成功");
        } else {
            return Result.fail("教学单元删除失败，课程不存在");
        }
    }
 /*   @RequiresAuthentication
    @GetMapping("/unit/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        CourseLearnUnit courseLearnUnit = courseLearnUnitService.getById(id);
        Assert.notNull(courseLearnUnit, "该单元已被删除");

        return Result.succ(courseLearnUnit);
    }*/
}
